package com.tanhua.server.service.impl;

import com.github.dozermapper.core.Mapper;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserFocusApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;

import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private UserFocusApi userFocusApi;

    @Autowired
    Mapper mapper;

    //保存用户信息
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new RuntimeException("不包含人脸");
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    @Override
    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

//        UserInfoVo vo = new UserInfoVo();
//
//        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        UserInfoVo vo = mapper.map(userInfo, UserInfoVo.class);

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    @Override
    public Counts counts() {
        Counts counts = userLikeApi.countsByUserId(UserHolder.getUserId());

        return counts;
    }

    @Override
    public PageResult friends(Integer page, Integer pagesize, String type, String nickname) {
        Long userId = UserHolder.getUserId();
        PageResult pageResult = new PageResult();
        if ("1".equals(type)) {
            //1 互相关注
            pageResult = userLikeApi.eachLove(page,pagesize,userId);
            List<UserLike> items = (List<UserLike>) pageResult.getItems();
            pageResult = getPageResult(pageResult, null, items, nickname,null);
        } else if ("2".equals(type)) {
            //2 我关注
            pageResult = userLikeApi.love(page,pagesize,userId);
            List<UserLike> items = (List<UserLike>) pageResult.getItems();
            pageResult = getPageResult(pageResult, null, items, nickname,null);
        } else if ("3".equals(type)) {
            //3 粉丝
            pageResult = userLikeApi.fenLove(page,pagesize,userId);
            List<UserLike> items = (List<UserLike>) pageResult.getItems();
            pageResult = getPageResult(pageResult, null, items, nickname,type);
        } else if ("4".equals(type)) {
            //4 谁看过我
            pageResult = visitorsApi.myVisitors(page,pagesize,userId);
            List<Visitors> items = (List<Visitors>) pageResult.getItems();
            pageResult = getPageResult(pageResult, items, null, nickname,null);
        }

        return pageResult;
    }

    @Override
    public UserInfo findByUserId(Long userId) {
        return userInfoApi.findById(userId);
    }

    @Override
    public void saveUserLike(String uid) {
        Long userId = UserHolder.getUserId();
        Boolean falg = userLikeApi.find(userId,uid);
        if (falg){
            throw new BusinessException(ErrorResult.loveError());
        }
        UserLike userLike = new UserLike();
        userLike.setUserId(userId);
        userLike.setLikeUserId(Long.valueOf(uid));
        userLike.setIsLike(true);

        userLikeApi.save(userLike);
    }

    @Override
    public void removeUserLike(String uid) {
        Long userId = UserHolder.getUserId();

        userLikeApi.remove(userId,uid);
    }


    private PageResult getPageResult(PageResult pageResult, List<Visitors> visitors, List<UserLike> userLikes, String nickname, String type) {
        if (visitors!= null){
            List<Long> ids = visitors.stream().map(visitor -> visitor.getVisitorUserId()).collect(Collectors.toList());
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
            List<FriendVo> vos = visitors.stream().filter(c -> map.get(c.getVisitorUserId()) != null)
                    .map(c -> FriendVo.init(map.get(c.getVisitorUserId()), c, null))
                    .collect(Collectors.toList());
            if (nickname!=null){
                vos = vos.stream().filter(friendVo -> nickname.contains(friendVo.getNickname())).collect(Collectors.toList());
            }
            pageResult.setItems(vos);
        }
        if (userLikes!= null){
            List<Long> ids = null;
            List<FriendVo> vos = null;
            if ("3".equals(type)) {
                ids = userLikes.stream().map(userLike -> userLike.getUserId()).collect(Collectors.toList());
                Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
                vos = userLikes.stream().filter(c -> map.get(c.getUserId()) != null)
                        .map(c -> FriendVo.init(map.get(c.getUserId()), null, c))
                        .collect(Collectors.toList());

                List<UserLike> likes = userLikeApi.loves(userLikes.get(0).getLikeUserId());
                List<Long> list = likes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
                for (FriendVo vo : vos) {
                    if (!list.contains(Long.valueOf(vo.getId()))) {
                        vo.setAlreadyLove(false);
                    }
                }
            }else {
                ids = userLikes.stream().map(userLike -> userLike.getLikeUserId()).collect(Collectors.toList());
                Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
                vos = userLikes.stream().filter(c -> map.get(c.getLikeUserId()) != null)
                        .map(c -> FriendVo.init(map.get(c.getLikeUserId()), null, c))
                        .collect(Collectors.toList());
            }
            if (nickname!=null){
                vos = vos.stream().filter(friendVo -> nickname.contains(friendVo.getNickname())).collect(Collectors.toList());
            }
            pageResult.setItems(vos);
        }
        return pageResult;
    }
}